package com.circus.trace.controller.material;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.circus.trace.bean.material.area.Storage;
import com.circus.trace.biz.material.area.StorageService;
import com.circus.trace.controller.BaseController;
import com.circus.trace.ext.shiro.anno.SINORequiresPermissions;
import com.circus.trace.vo.InstallPermission;

import club.zhcs.common.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("storage")
public class StorageController extends BaseController {

	@Autowired
	StorageService storageService;

	@GetMapping("list")
	@SINORequiresPermissions(InstallPermission.STORAGE_LIST)
	@ApiOperation(value = "仓储分页列表")
	public Result list(@RequestParam(value = "page", defaultValue = "1") @ApiParam("页码") int page) {
		return Result.success().addData("pager", storageService.searchByPage(fixPage(page), Cnd.where("enabled", "=", true).desc("id")));
	}

	@GetMapping("search")
	@SINORequiresPermissions(InstallPermission.STORAGE_LIST)
	@ApiOperation(value = "仓储分页检索")
	public Result search(@RequestParam("key") @ApiParam("搜索关键字") String key, @RequestParam(value = "page", defaultValue = "1") @ApiParam("页码") int page) {
		return Result.success()
				.addData("pager", storageService.searchByKeyAndPage(
						fixSearchKey(key),
						fixPage(page),
						Cnd.where("enabled", "=", true),
						"name")
						.addParam("key", key));
	}

	@PostMapping(value = "add")
	@SINORequiresPermissions(InstallPermission.STORAGE_ADD)
	@ApiOperation(value = "新增仓储")
	public Result save(@RequestBody Storage storage) {
		return storageService.save(storage) == null ? Result.fail("保存仓储信息失败!") : Result.success().addData("storage", storage);
	}

	@PostMapping(value = "edit")
	@SINORequiresPermissions(InstallPermission.STORAGE_EDIT)
	public Result edit(@RequestBody Storage storage) {
		return storageService.update(storage) == 1 ? Result.success() : Result.fail("更新仓库失败!");
	}
	
	/**
	 * 删除仓库
	 * 
	 * @param id
	 *            仓库id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@SINORequiresPermissions(value = { InstallPermission.AREA_DELETE })
	@ApiOperation("删除仓库")
	public Result delete(@PathVariable("id") @ApiParam("仓库id") long id) {
		return storageService.update(Chain.make("enabled", false), Cnd.where("id", "=", id)) == 1 ? Result.success() : Result.fail("删除仓库失败!");
	}
}
